<?php
/*
 * @Author: 子不予 hjm353973814@qq.com
 * @Date: 2025-08-29 11:08:40
 * @LastEditors: 子不予 hjm353973814@qq.com
 * @LastEditTime: 2025-08-29 14:33:05
 * @FilePath: \xixiangfang\application\common\model\GoodsCategory.php
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
 */

namespace app\common\model;

use think\Model;

/**
 * 商品分类
 */
class GoodsCategory extends Model
{
    
    /**
     * 获取商品分类树状结构
     */
    public static function get_category_tree()
    {
        // 从数据库获取所有分类
        $categories = self::where('is_show', 1)->order('parent_id asc, sort asc')->select();
        
        // 构建树状结构
        $tree = self::buildCategoryTree($categories);
        
        return $tree;
    }

    /**
     * 构建分类树状结构
     * @param array $categories 分类数据
     * @param int $parentId 父级ID
     * @return array
     */
    private static function buildCategoryTree($categories, $parentId = 0)
    {
        $tree = [];
        
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                $children = self::buildCategoryTree($categories, $category['id']);
                if (!empty($children)) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }
        return $tree;
    }

    /**
     * 获取指定分类下的子分类（支持多层级）
     */
    public static function get_sub_categories($param)
    {
        $categoryId = isset($param['category_id']) ? (int)$param['category_id'] : 0;
        
        // 获取所有分类
        $categories = self::here('is_show', 1)->order('parent_id asc, sort asc')->select();
        
        // 获取指定分类的所有子分类
        $subCategories = self::getChildrenCategories($categories, $categoryId);
        
        return $subCategories;
    }

    /**
     * 递归获取所有子分类
     * @param array $categories 所有分类数据
     * @param int $parentId 父级ID
     * @return array
     */
    private function getChildrenCategories($categories, $parentId)
    {
        $children = [];
        
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                $category['children'] = self::getChildrenCategories($categories, $category['id']);
                $children[] = $category;
            }
        }
        
        return $children;
    }
}